package controller

import (
	"GoAdmin/common"
	"GoAdmin/dto"
	"GoAdmin/model"
	"GoAdmin/response"
	"GoAdmin/util"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Register(c *gin.Context) {
	db := common.InitDB()

	//使用map获取请求的参数
	//var requestMap = make(map[string]string)
	//json.NewDecoder(c.Request.Body).Decode(&requestMap)

	//使用结构体来绑定请求参数
	//var requestUser = model.User{}
	//json.NewDecoder(c.Request.Body).Decode(&requestUser)

	//使用Gin框架下的bind函数
	//var requestUser = model.User{}
	//c.Bind(&requestUser)

	//以下三行代码为上述参数解析共用
	//name := requestUser.Name
	//telephone := requestUser.Telephone
	//password := requestUser.Password

	//使用Form获取请求参数
	name := c.PostForm("name")
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")

	if len(telephone) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号为11位")
		return
	}

	if len(password) == 0 || len(password) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码必须大于6位")
		return
	}
	if len(name) == 0 {
		name = util.RandomString(10)
	}

	log.Println(name, telephone, password)

	if isTeleponeIsExit(db, telephone) {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户已存在")
		return
	}
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统错误")
	}

	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hashPassword),
	}
	db.Create(&newUser)

	response.Success(c, nil, "注册成功")
}

func Login(c *gin.Context) {
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")

	if len(telephone) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号为11位")
		return
	}

	if len(password) == 0 || len(password) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码必须大于6位")
		return
	}
	db := common.GetDB()
	var user model.User
	db.Where("telephone=?", telephone).First(&user)

	if user.ID == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	//这里实际上是两行并成一行的逻辑
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.Response(c, http.StatusUnprocessableEntity, 400, nil, "密码错误")
		return
	}

	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统错误")
		log.Printf("token generate error,%v", err)
		return
	}

	response.Success(c, gin.H{
		"token": token,
	}, "登录成功")
}

func GetUserInfo(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	response.Success(ctx, gin.H{"user": dto.ToUserDto(user.(model.User))}, "获取用户信息成功")
}

func isTeleponeIsExit(db *gorm.DB, phone string) bool {
	var user model.User
	db.Where("telephone=?", phone).First(&user)

	if user.ID != 0 {
		return true
	}
	return false
}
